import requests
from db import utils
from logger import logger
from sub_events.base_event import BaseEvent

LOGGER = logger.CustomLogger()

TARGET_URL = "http://121.43.52.4:6001/check_header_file"


class HeaderFileCheck(BaseEvent):
    def __init__(self, **kwargs):
        super().__init__(**kwargs)
        self.event_name_zh: str = "头文件引用计数检查"
        self.event_name_en: str = "Header File Check"

    def execute(self):
        force_status = utils.get_force_pass_status_by_hook(self.hook, self.event_name_en)
        if force_status:
            return
        try:
            body = {
                "repo_name": self.hook.repo_name,
                "pr_number": self.hook.pr_number
            }
            response = requests.post(
                TARGET_URL,
                json=body,
                timeout=5
            )

            # 检查请求是否成功
            if response.status_code == 200:
                data = response.json()
                check_result = data.get("status")
                if check_result == 'check pass':
                    utils.update_event_force_pass(self.hook, self.event_name_en, "")
                elif check_result == 'check start':
                    self.comment = "头文件引用检查中，稍后返回结果。\n\nCheck result will return as a comment soon."
                    self.failed = True
                else:
                    self.comment = "头文件引用检查失败, 请参考wiki处理：https://gitcode.com/openharmony/arkui_ace_engine/wiki/arkui_ace_engine%E4%BB%93%E5%BA%93%E5%A2%9E%E5%BC%BA%E9%97%A8%E7%A6%81%E6%A3%80%E6%9F%A5%E8%AF%B4%E6%98%8E.md#%E5%A4%B4%E6%96%87%E4%BB%B6%E5%BC%95%E7%94%A8%E6%AC%A1%E6%95%B0%E6%A3%80%E6%9F%A5%E8%AF%A6%E7%BB%86%E8%AF%B4%E6%98%8E"
                    self.failed = True
                    LOGGER.error(f"[{self.hook.pr_number}] 头文件引用检查失败, check_result 是[{check_result}]")

            else:
                self.comment = "头文件引用未能成功检查，暂不拦截。"
                utils.update_event_force_pass(self.hook, self.event_name_en, "")
                LOGGER.error(f"[{self.hook.pr_number}] 头文件引用检查失败, 请求错误码[{response.status_code}]")
                LOGGER.error(f"[{self.hook.pr_number}] 头文件引用检查失败, 请求错误信息[{response.text}]")

        except requests.exceptions.Timeout:
            self.comment = "头文件引用检查超时，请参考wiki处理：https://gitcode.com/openharmony/arkui_ace_engine/wiki/arkui_ace_engine%E4%BB%93%E5%BA%93%E5%A2%9E%E5%BC%BA%E9%97%A8%E7%A6%81%E6%A3%80%E6%9F%A5%E8%AF%B4%E6%98%8E.md#%E5%A4%B4%E6%96%87%E4%BB%B6%E5%BC%95%E7%94%A8%E6%AC%A1%E6%95%B0%E6%A3%80%E6%9F%A5%E8%AF%A6%E7%BB%86%E8%AF%B4%E6%98%8E"
            self.failed = True
            LOGGER.error(f"[{self.hook.pr_number}] 头文件引用检查超时")
        except requests.exceptions.RequestException as e:
            self.comment = "头文件引用未能成功检查，暂不拦截。"
            utils.update_event_force_pass(self.hook, self.event_name_en, "")
            LOGGER.error(f"[{self.hook.pr_number}] 请求发生错误: {e}")
